#include <brpc/channel.h>
#include "echo.pb.h"
#include <memory>
#include <string>
#include <iostream>
#include <butil/logging.h>
#include "../../etcd/etcd.hpp"
#include "../channel.hpp"

void callback(brpc::Controller *cntl, example::EchoRequest *request, example::EchoResponse *response)
{
    if (!cntl->Failed())
    {
        std::cout << "响应：>" << response->message() << std::endl;
    }
    else
    {
        std::cout << "错误：" << cntl->ErrorText() << std::endl;
    }
    // 释放资源
    delete cntl;
    delete request;
    delete response;
}

int main()
{
    init_mylogger(false, "test", "", 0, false);
    // 实例化通信信道对象
    // class Channel : public ChannelBase
    // class ChannelBase : public google::protobuf::RpcChannel
    // brpc::Channel chanel;

    // 关注的服务
    ns_server_manager::ServersManager folled_servers(std::vector<std::string>({"./Echo"}));
    // server先启动，client后启动 (先注册，再发现)
    std::unordered_map<std::string, std::string> servers;
    ns_etcd_client::Discovery dis("127.0.0.1:2379", "./Echo", servers,
                                  std::bind(&ns_server_manager::ServersManager::Online, &folled_servers, std::placeholders::_1, std::placeholders::_2),
                                  std::bind(&ns_server_manager::ServersManager::Offline, &folled_servers, std::placeholders::_1, std::placeholders::_2),
                                  true);

    // 把发现的服务先进行上线
    for (auto &e : servers)
    {
        folled_servers.Online(e.first, e.second);
    }

    // 选择信道
    while (true)
    {
        auto channel = folled_servers.ChooseOneChannel("./Echo");
        if (channel == nullptr)
        {
            sleep(1);
            continue;
        }

        // 初始化：ip, addr, options
        /*
        brpc::ChannelOptions cops;//参数配置
        if (chanel.Init("127.0.0.1:8080", &cops) == 1)
        {
            std::cout << "chanel.Init() failed!" << std::endl;
            return -1;
        }
        */

        // 实例化 客户端 对象
        std::unique_ptr<example::EchoService_Stub> client = std::make_unique<example::EchoService_Stub>(channel.get());

        // std::cout << "输入：>";
        std::string in = "hello!";
        // std::getline(std::cin, in);

        // 为每个请求创建新的 Controller、Request 和 Response 对象
        brpc::Controller *cntl = new brpc::Controller();
        example::EchoRequest *request = new example::EchoRequest();
        example::EchoResponse *response = new example::EchoResponse();

        request->set_message(in);

        // 创建回调函数
        google::protobuf::Closure *done = brpc::NewCallback(callback, cntl, request, response);

        // 异步调用
        client->Echo(cntl, request, response, done);

        sleep(1);
    }

    return 0;
}